package com.example.agboxdemo.controller;

import cn.hutool.core.io.FileUtil;
import com.example.agboxdemo.entity.vo.ResultVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * @author hnn
 * @version 1.0
 * @date 2025-07-07 15:07
 */
@Slf4j
@RequiredArgsConstructor
@RestController
public class DeviceParkingController {

    private final ObjectMapper objectMapper;

    @PostMapping("/device/parking")
    public ResultVO work(@RequestParam("key") String key, @RequestParam("json") String json, MultipartHttpServletRequest request) {
        log.info("recv key:{},json:{}", key, json);
        ObjectNode on = objectMapper.createObjectNode();

        // 获取所有上传的文件
        java.util.Map<String, MultipartFile> fileMap = request.getFileMap();

        for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
            String fieldName = entry.getKey();
            MultipartFile file = entry.getValue();

            if (!file.isEmpty()) {
                log.info("接收到文件 [字段名: {}] - 文件名: {}, 大小: {}",
                        fieldName, file.getOriginalFilename(), file.getSize());
                try {
                    FileUtil.writeBytes(file.getBytes(), Paths.get("pic", file.getOriginalFilename()).toFile());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        on.put("datetime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return new ResultVO<ObjectNode>(on);
    }
}
